package com.taofengsdk.okhttp.response;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.taofengsdk.okhttp.exception.OkHttpException;
import com.taofengsdk.okhttp.listener.DisposeDataHandle;
import com.taofengsdk.okhttp.listener.DisposeDataListener;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by tao on 17-3-12.
 *
 * @function 自定义回调并解析json文件
 */

public class CommonJsonCallback implements Callback {

    protected final String RESULT_CODE = "code";
    protected final String Result_CODE_VALUE = "0";
    protected final String ERROR_MSG = "emsg";
    protected final String EMPTY_MSG = "";

    protected final int NETWORK_ERROR = -1;
    protected final int JSON_ERROR = -2;
    protected final int OTHER_ERROR = -3;

    private Handler mDeliveryHandler;
    private DisposeDataListener mListener;
    private Class<?> mClass;

    public CommonJsonCallback(DisposeDataHandle handle) {
        this.mListener = handle.mListener;
        this.mClass = handle.mClass;
        this.mDeliveryHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void onFailure(Call call, final IOException e) {
        mDeliveryHandler.post(new Runnable() {
            @Override
            public void run() {
                mListener.onFailure(new OkHttpException(NETWORK_ERROR, e.getMessage()));
            }
        });
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        final String result = response.body().string();
        mDeliveryHandler.post(new Runnable() {
            @Override
            public void run() {
                handleResponse(result);
            }
        });

    }

    private void handleResponse(Object responseObj) {
        if (responseObj == null || TextUtils.isEmpty(responseObj.toString().trim())) {
            mListener.onFailure(new OkHttpException(NETWORK_ERROR, EMPTY_MSG));
            return;
        }
        try {

            JSONObject result = new JSONObject(responseObj.toString());
            //从json中取出响应码，若为0，则为正确的响应
            //不需要解析，直接返回数据到应用层
            if (mClass == null) {
                mListener.onSuccess(responseObj);
            } else {
                //将json数据转为实体对象
                Gson gson = new Gson();
                Object object = gson.fromJson(String.valueOf(result), mClass);
                //正确的转为了实体对象
                if (object != null) {
                    mListener.onSuccess(object);
                } else {
                    mListener.onFailure(new OkHttpException(JSON_ERROR, EMPTY_MSG));
                }
            }

        } catch (Exception e) {
            mListener.onFailure(new OkHttpException(NETWORK_ERROR, e.getMessage()));
        }

    }
}
